package com.example.ywj.toutiao.fragments;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.material.tabs.TabLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.example.ywj.toutiao.AddTitleActivity;
import com.example.ywj.toutiao.IssueActivity;
import com.example.ywj.toutiao.R;
import com.example.ywj.toutiao.SearchActivity;
import com.example.ywj.toutiao.bean.Key;
import com.example.ywj.toutiao.bean.Lists;
import com.example.ywj.toutiao.bean.Title;
import com.example.ywj.toutiao.utils.Constant;
import com.example.ywj.toutiao.utils.MyFragmentPageAdapter2;
import com.example.ywj.toutiao.utils.PopWindowAdapter1;
import com.example.ywj.toutiao.utils.ResponseApi;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class HomeFragment extends Fragment {
    private static final String TAG = "HomeFragment";
    private String baseUrl = Constant.BASEURL;
    private TabLayout mTabLayout;
    private ViewPager vp;
    private List<String> strTitle = new ArrayList<>();
    private ArrayList<Fragment> frags = new ArrayList<>();
    private MyFragmentPageAdapter2 myFragmentPageAdapter2;
    public TextView textView_plus;
    public GridView bottom_dialog_gridView1;
     EditText et;
     public List<Title> titleList;
     public PopupWindow popupWindow;
     public LinearLayout layout;
    public String[] add ={"发图文","拍小视频","发视频","提问","开直播","爆料"};
    public List<Lists> liststr = new ArrayList<>();
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.home_fragment, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        initView();
        getData();
        getKeyData();
        super.onActivityCreated(savedInstanceState);
    }

    //Handler
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            //super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    addTabToTabLayout(strTitle);
                    mTabLayout.setupWithViewPager(vp);
                    myFragmentPageAdapter2 = new MyFragmentPageAdapter2(getActivity().getSupportFragmentManager(),strTitle);
                    vp.setAdapter(myFragmentPageAdapter2);
                    vp.setOffscreenPageLimit(strTitle.size());
                    break;
            }
        }
    };
    //获取标签数据
    private void getData(){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.getData();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200 && obj.has("data")){
                    JsonArray data = obj.getAsJsonArray("data");
                    Gson gson = new Gson();
                    titleList = gson.fromJson(data,new TypeToken<ArrayList<Title>>(){}.getType());
                    sendData(titleList);
                }else {
                    Log.i(TAG, "onResponse: 出错了");
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: 请求失败");
            }
        });
    }
    public void getKeyData(){
        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
        ResponseApi responseApi = retrofit.create(ResponseApi.class);
        Call<ResponseBody> call = responseApi.getKeyByType(1);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String json = null;
                try {
                    json = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "onResponse: "+json);
                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                Integer code = obj.get("statusCode").getAsInt();
                if(code == 200&& obj.has("data")){
                    JsonArray data = obj.getAsJsonArray("data");
                    Gson gson = new Gson();
                    List<Key> list = gson.fromJson(data,new TypeToken<ArrayList<Key>>(){}.getType());
                    //Log.i(TAG, "onResponse: "+list);
                    int index = (int)(0+Math.random()*((list.size()-1)-0+1));
                    //Log.i(TAG, "onResponse: "+index);
                    String str = list.get(index).getKey();
                    Log.i(TAG, "onResponse: "+list.get(index).getKey());
                    //Log.i(TAG, "onResponse: "+str);
                    et.setHint(str);
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.i(TAG, "onFailure: 请求失败");
            }
        });
    }
    private void sendData(List<Title> list){
        for(int i = 0;i<list.size();i++){
            strTitle.add(list.get(i).getTitle());
        }
        Message message = new Message();
        message.what = 0;
        handler.sendMessage(message);
    }
    @Override
    public void onStart() {
        super.onStart();
    }
    public void initView(){
        et = getActivity().findViewById(R.id.editText);
        TextView tvShow = getActivity().findViewById(R.id.fangdajing);
        TextView tv_plus = getActivity().findViewById(R.id.textView_plus);
        TextView tv_cam = getActivity().findViewById(R.id.cam);
        final EditText et = getActivity().findViewById(R.id.editText);
        vp = getActivity().findViewById(R.id.viewpager_home);
        Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "iconfont.ttf");
        tvShow.setTypeface(font);
        tv_plus.setTypeface(font);
        tv_cam.setTypeface(font);
        tvShow.setText(getResources().getString(R.string.font5));
        tv_plus.setText(getResources().getString(R.string.font7));
        tv_cam.setText(getResources().getString(R.string.font6));
        mTabLayout = getActivity().findViewById(R.id.tl_main);
        et.setOnFocusChangeListener(new View.OnFocusChangeListener(){
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    Bundle bundle = new Bundle();
                    //Log.i(TAG, "onFocusChange: "+et.getText().toString());
                    EditText et1 = v.findViewById(R.id.editText);
                    bundle.putString("key",String.valueOf(et1.getHint()));
                    Intent intent = new Intent(v.getContext(),SearchActivity.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    getActivity().overridePendingTransition(0, 0);
                    v.clearFocus();
                }
            }
        });
        textView_plus = getActivity().findViewById(R.id.textView_plus);
        textView_plus.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(),AddTitleActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.translate_dialog_in,0);
            }
        });
        tv_cam.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                int y = new Double(mTabLayout.getBottom() * 3.6/ 2).intValue() ;
                int x = getActivity().getWindowManager().getDefaultDisplay().getWidth()-1050;
                Log.i(TAG, "onClick: "+x);
                showPopWindow(x,y);
            }
        });

    }
    public void showPopWindow(int x,int y){

        Integer picArr[] = {R.string.pic,R.string.huo,R.string.pvideo,R.string.ask,R.string.video,R.string.laba};
        for(int i=0;i<add.length;i++){
            liststr.add(new Lists(add[i],picArr[i]));
        }
        Log.i(TAG, "showPopWindow: "+liststr);
        PopWindowAdapter1 popWindowAdapter1 = new PopWindowAdapter1(liststr);
        layout = (LinearLayout) LayoutInflater.from(getContext()).inflate(
                R.layout.popwindow_layout, null);
        ListView listView = layout.findViewById(R.id.popListView);
        listView.setAdapter(popWindowAdapter1);
        popupWindow = new PopupWindow(getContext());
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#636363")));
        popupWindow
                .setWidth(new Double(getActivity().getWindowManager().getDefaultDisplay().getWidth() / 2.8).intValue());
        popupWindow.setHeight(860);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setContentView(layout);
        popupWindow.showAtLocation(getActivity().findViewById(R.id.toolbar),
                Gravity.TOP, x, y);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0:
                        Intent intent = new Intent(view.getContext(),IssueActivity.class);
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.translate_dialog_in,0);
                        popupWindow.dismiss();
                }
            }
        });
    }
    private void addTabToTabLayout(List<String> list) {
        for (int i = 0; i < list.size(); i++) {
            mTabLayout.addTab(mTabLayout.newTab().setText(list.get(i)));
        }
    }

}
